package cn.changein.framework.fastDFS;

import cn.changein.framework.kernel.model.response.ResponseData;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @param

 * @description 阿里云存储上传文件工具类
 * @date 10:44 2019/5/24
 * @return
 **/
public class AliOosUtil {
    // Endpoint以杭州为例，其它Region请按实际情况填写。https://oss-cn-hangzhou.aliyuncs.com
    public static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
//    public static String accessKeyId = "LTAI4G5w5YUEqSMJnVVDAbqG";
//    public static String accessKeySecret = "SEU84emz2cj58KpmWv3beWTah2K58s";
//    public static String bucketName = "purewin-oss";
    public static String accessKeyId = "LTAI4GHo5sd45xse5ktJkJ8g";
    public static String accessKeySecret = "rrGDK0wt8oYF3WSb8zYF51ybuoyeMK";
    public static String bucketName = "vipshop-bucket";

    public static void main(String[] args) throws FileNotFoundException {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传文件流。
        InputStream inputStream = new FileInputStream("C:\\Users\\Hsu\\Desktop\\wechat.png");
        ossClient.putObject(bucketName, "wechat.png", inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * @param fileName    文件名,即访问名 #示例:https://image.bolon.cn/BJ3056B11_1.jpg
     * @param inputStream 文件流
     * @return cn.pw.base.result.TableResult

     * @description 根据文件名和文件流, 上传文件
     * @date 10:45 2019/5/24
     **/
    public static ResponseData upload(String fileName, InputStream inputStream) {
        try {
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, fileName, inputStream);
            ossClient.shutdown();
        } catch (Exception e) {
            return ResponseData.error("");
        }
         /*ResponseMessage response = putObjectResult.getResponse();
         TableResult tableResult = new TableResult();
         if (response.isSuccessful()) {
                tableResult.setCode(0);
         } else {
                String errorResponseAsString = response.getErrorResponseAsString();
                tableResult.setMsg(errorResponseAsString);
                tableResult.setCode(1);
         }*/
        //关闭OSSClient
        return ResponseData.success();
    }

    // 下载文件

    /**
     * @param filename
     * @throws OSSException
     * @throws ClientException
     */
    public static void downloadFile(String filename, HttpServletResponse response) {
        if (StrUtil.isBlank(filename)) {
            return;
        }
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, filename);
        OSSObject ossObject = ossClient.getObject(getObjectRequest);
        if (ossObject != null) {
            InputStream inputStream = ossObject.getObjectContent();
            int buffer = 1024 * 10;
            byte data[] = new byte[buffer];
            try {
                response.setContentType("application/octet-stream");
                // 文件名可以任意指定
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));//将文件名转为ASCLL编码
                int read;
                while ((read = inputStream.read(data)) != -1) {
                    response.getOutputStream().write(data, 0, read);
                }
                response.getOutputStream().flush();
                response.getOutputStream().close();
                ossObject.close();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
